from django.db import connection
from rest_framework import serializers

from blog.models import Article, User, Comment


class UserSimpleSerializer(serializers.ModelSerializer):
    '''用户简单序列化器'''

    class Meta:
        model = User
        fields = ('uname',)


class ComentSimpleSerializer(serializers.ModelSerializer):
    '''用户简单序列化器'''

    class Meta:
        model = Comment
        fields = '__all__'


class ArticleSerializer(serializers.ModelSerializer):
    '''文章序列化器'''

    authors = serializers.SerializerMethodField()
    atime = serializers.SerializerMethodField()
    #新增评论数字段
    coments = serializers.SerializerMethodField()

    @staticmethod
    def get_atime(obj):
        # 重写时间格式
        return obj.atime.strftime('%Y-%m-%d')

    @staticmethod
    def get_authors(obj):
        # 重写作者
        return UserSimpleSerializer(obj.author).data

    @staticmethod
    def get_coments(obj):
        # 游标对象把评论数查出
        with connection.cursor() as cursor:
            cursor.execute('SELECT carticle,COUNT(cno) from tb_comment GROUP BY carticle;')
            agents = cursor.fetchall()
            #将结果字典化，并返回指定文章的评论。
            cc = [dict([('carticle', i[0]), ('count', i[1])]) for i in agents]
            for x in cc:
                if obj.ano == x['carticle']:
                    return x['count']





    class Meta:
        model = Article
        exclude = ('author',)


class ArticleFilterSet():
    '''查询和排序'''
    pass
